/**
 * Project Name:emm-website
 * File Name:BusinessChangeController.java
 * Package Name:com.emm.yixun.website.controller.marketing
 * Date:2017年11月13日下午1:37:22
 * Copyright (c) 2017, shihao.liu@qiaofang.info All Rights Reserved.
 *
*/

package com.emm.yixun.website.controller.marketing;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.*;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.marketing.service.BusinessChangeServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.customer.SubscribeService;
import com.emm.yixun.website.utils.ExcelUtil;

/**
 * ClassName:BusinessChangeController <br/>
 * Date:     2017年11月13日 下午1:37:22 <br/>
 * @author   Administrator
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
@Controller
@RequestMapping(value = "/marketing/businessChange/")
public class BusinessChangeController extends BaseController<BusinessChange>{
	
	@Autowired
	private BusinessChangeServiceFacade businessChangeServiceFacade;
	
	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;

	@Autowired
	private CustomerServiceFacade customerServiceFacade;

	@Autowired
	private FamilyMemberServiceFacade familyMemberServiceFacade;

	@Autowired
	private SignedServiceFacade signedServiceFacade;

	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;

	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;

	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;

	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;

	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;

	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;

    @Autowired
    private ProjectPremisesServiceFacade projectPremisesServiceFacade;
	/**
	 * 
	 * getModelByPage:(查询列表数据). <br/>
	 * @author Administrator
	 * @param businessChangeDto
	 * @param page
	 * @param limit
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "getModelByPage")
	public @ResponseBody Page<BusinessChange> getModelByPage(BusinessChangeDto businessChangeDto,Integer page, Integer limit){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:list"))){
				User user = ShiroUtil.getCurrentUser();
				businessChangeDto.setMerchantId(user.getMerchantId());
				businessChangeDto.setPermissionUserId(user.getId());
				businessChangeDto.setExport(false);
				Page<BusinessChange> response = businessChangeServiceFacade.queryBusinessChangeInfo(businessChangeDto, PageUtil.begin(page, limit), limit);
				if(response.getSuccess()&&response.getRows()!=null){
					response.setPageNumber(page);
					return response;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("退换列表查询异常:",e);
		}
		return new Page<BusinessChange>();
	}


	/**
	 * 
	 * businessChangeExport:(退换列表导出). <br/>
	 * @author Administrator
	 * @param value
	 * @param response
	 * @param request
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "businessChangeExport")
	public void businessChangeExport(String value,HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
				String jsonStr=URLDecoder.decode(value,"utf-8");
				BusinessChangeDto businessChangeDto = JSONObject.parseObject(jsonStr,BusinessChangeDto.class);
				User user = ShiroUtil.getCurrentUser();
				businessChangeDto.setMerchantId(user.getMerchantId());
				businessChangeDto.setPermissionUserId(user.getId());
				businessChangeDto.setExport(true);
				String[] name = new String[]{"退换信息"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"经办日前","退房日期","客户名称","客户手机","房号","户型","计价面积","合同金额","已收金额","退款金额","经纪人",
						"业务状态","审核状态"
						};
				headerList.add(header);
				Page<BusinessChange> responseList = businessChangeServiceFacade.queryBusinessChangeInfo(businessChangeDto, PageUtil.begin(1, 10), 10);
				List<BusinessChange> businessChangeList = responseList.getRows();
				List<Map<String, String>> listMap = subscribeService.businessChangeExport(businessChangeList, header);
				list.add(listMap);
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
		} catch (Exception e) {
			logger.error("退换列表导出异常:",e);
		}
	}

	@RequestMapping(value="toBusinessChangeList")
	public String toBusinessChangeList(ModelMap map){
//		map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "signed:list:all"));
        ProjectPremisesDto premisesDto = new ProjectPremisesDto();
        premisesDto.setProjectId(153l);
        ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
        map.put("premisesList",dataList.getEntity());
		return "/report/changeHousesReport";
	}

	@RequestMapping(value="toBusinessOutList")
	public String toBusinessOutList(ModelMap map){
//		map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "signed:list:all"));
        ProjectPremisesDto premisesDto = new ProjectPremisesDto();
        premisesDto.setProjectId(153l);
        ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
        map.put("premisesList",dataList.getEntity());
		return "/report/outHousesReport";
	}

	@RequestMapping(value="toPaymentStagesList")
	public String toCustomerInfoList(ModelMap map){
//		map.put("permitBtn", doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "signed:list:all"));
        ProjectPremisesDto premisesDto = new ProjectPremisesDto();
        premisesDto.setProjectId(153l);
        ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
        map.put("premisesList",dataList.getEntity());
		return "/report/paymentStagesReport";
	}
	/**
	 *
	 * getModelByPage:(查询列表数据). <br/>
	 * @author Administrator
	 * @param pageNum
	 * @param pageSize
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "getModelByPageNew")
	public @ResponseBody AjaxRes getModelByPageNew( HttpServletRequest request,Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:list"))){
				User user = ShiroUtil.getCurrentUser();

                BusinessReceiveRefundDto businessReceiveRefundDto = new BusinessReceiveRefundDto();
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                businessReceiveRefundDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    businessReceiveRefundDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    businessReceiveRefundDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				if(businessReceiveRefundDto.getProjectId() ==null){
					businessReceiveRefundDto.setProjectId(153l);
				}

				businessReceiveRefundDto.setExport(false);
				Page<BusinessReceiveRefund> response = businessChangeServiceFacade.queryBusinessChangeInfoNew(businessReceiveRefundDto, PageUtil.begin(pageNum, pageSize), pageSize);
                response.setPageNumber(pageNum);
                ar.setSucceed(response);

			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("退换列表查询异常:",e);
		}
		return ar;
	}

	@RequestMapping(value = "businessChangeExportNew")
	public void businessChangeExportNew( HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
//				String jsonStr=URLDecoder.decode(value,"utf-8");
//				BusinessReceiveRefundDto businessReceiveRefundDto = JSONObject.parseObject(jsonStr,BusinessReceiveRefundDto.class);
				User user = ShiroUtil.getCurrentUser();

                BusinessReceiveRefundDto businessReceiveRefundDto = new BusinessReceiveRefundDto();
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                businessReceiveRefundDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    businessReceiveRefundDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    businessReceiveRefundDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				businessReceiveRefundDto.setExport(true);
				String[] name = new String[]{"换房信息"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"原购买房间","变更前订房日期","客户姓名","交易状态","原面积","原成交价","变更类型","申请人","申请时间","换房后新房间",
						"变更后订房日期","新面积","新成交价","审批状态"/*,"审批人"*/,"审批同意时间"
				};
				headerList.add(header);

				List<String[]> headerNumList = new ArrayList<String[]>();
				String[] headerNum = new String[]{

						"原成交价","新成交价","原面积","新面积"

				};
				headerNumList.add(headerNum);

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				if(businessReceiveRefundDto.getProjectId() ==null){
					businessReceiveRefundDto.setProjectId(153l);
				}
				businessReceiveRefundDto.setExport(false);
				Page<BusinessReceiveRefund> responseList = businessChangeServiceFacade.queryBusinessChangeInfoNew(businessReceiveRefundDto, PageUtil.begin(1, 99999), 99999);
				List<BusinessReceiveRefund> businessChangeList = responseList.getRows();
				List<Map<String, String>> listMap = businessChangeNewList(businessChangeList, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList,headerNumList, name, response);
			}
		} catch (Exception e) {
			logger.error("退换列表导出异常:",e);
		}
	}

	/**
	 * 组装导出换房数据
	 */
	private List<Map<String, String>> businessChangeNewList(List<BusinessReceiveRefund> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;
				BusinessReceiveRefund data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();

				map.put(head[n++]+"_"+i, data.getCombinedNameOld() != null ?data.getCombinedNameOld():""); //
				map.put(head[n++]+"_"+i, data.getSubscribeDate() != null ?data.getSubscribeDate().substring(0,10):""); //
                map.put(head[n++]+"_"+i, (data.getCustomerName() != null ?data.getCustomerName():"")+";"+(data.getCustomerFamilyName() != null ?data.getCustomerFamilyName():"")); //
				map.put(head[n++]+"_"+i, data.getBusinessNype() != null ?data.getBusinessNype():""); //
				map.put(head[n++]+"_"+i, data.getCalculateArea() != null ?data.getCalculateArea():""); //
				map.put(head[n++]+"_"+i, data.getSubscribeAmount() != null ?data.getSubscribeAmount():""); //
				map.put(head[n++]+"_"+i, "换房"); //
				map.put(head[n++]+"_"+i, data.getUserName() != null ?data.getUserName():""); //
				map.put(head[n++]+"_"+i, data.getCreateTime() != null ?data.getCreateTime():""); //
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():""); //
				map.put(head[n++]+"_"+i, data.getDateTime() != null ?data.getDateTime().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getBuildingArea() != null ?data.getBuildingArea():""); //
				map.put(head[n++]+"_"+i, data.getSubscribeAmountNew() != null ?data.getSubscribeAmountNew():""); //
				map.put(head[n++]+"_"+i, data.getAuditStatus() != null ?data.getAuditStatus():""); //
//				map.put(head[n++]+"_"+i, data.getUserName() != null ?data.getUserName():""); //
				map.put(head[n++]+"_"+i, data.getCheckDat() != null ?data.getCheckDat().substring(0,10):""); //

				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出签约回款提醒数据错误：{}",e);
		}
		return listMap;
	}
	/**
	 *
	 * getModelByPage:(查询列表数据). <br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "getOutByPageNew")
	public @ResponseBody AjaxRes getOutByPageNew( HttpServletRequest request,Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:list"))){
				User user = ShiroUtil.getCurrentUser();

                BusinessReceiveRefundDto businessReceiveRefundDto = new BusinessReceiveRefundDto();
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                businessReceiveRefundDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    businessReceiveRefundDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    businessReceiveRefundDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				businessReceiveRefundDto.setProjectId(153l);
				businessReceiveRefundDto.setExport(false);
				Page<BusinessReceiveRefund> response = businessChangeServiceFacade.queryBusinessOutInfoNew(businessReceiveRefundDto, PageUtil.begin(pageNum, pageSize), pageSize);
                response.setPageNumber(pageNum);
                ar.setSucceed(response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("换房列表查询异常:",e);
		}
		return ar;
	}

	@RequestMapping(value = "businessOutExport")
	public void businessOutExport(HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
//				String jsonStr=URLDecoder.decode(value,"utf-8");
//				BusinessReceiveRefundDto businessReceiveRefundDto = JSONObject.parseObject(jsonStr,BusinessReceiveRefundDto.class);
				User user = ShiroUtil.getCurrentUser();
                BusinessReceiveRefundDto businessReceiveRefundDto = new BusinessReceiveRefundDto();
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                businessReceiveRefundDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    businessReceiveRefundDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    businessReceiveRefundDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				businessReceiveRefundDto.setExport(true);
				String[] name = new String[]{"退房信息"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"客户姓名","购买房间","申请人","申请时间","审批状态","审批同意时间"
						,"交易类型","交易单状态","认购日期","客户来源","建筑面积","标准总价"
						,"标准单价","成交总价","成交单价","应收首付款","未退金额","置业顾问","原因分类","原因说明"
				};
				headerList.add(header);

				List<String[]> headerNumList = new ArrayList<String[]>();
				String[] headerNum = new String[]{

						"标准总价","标准单价","成交总价","成交单价","应收首付款","未退金额","建筑面积"

				};
				headerNumList.add(headerNum);

				businessReceiveRefundDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				if(businessReceiveRefundDto.getProjectId() ==null){
					businessReceiveRefundDto.setProjectId(153l);
				}
				businessReceiveRefundDto.setExport(false);
				Page<BusinessReceiveRefund> responseList = businessChangeServiceFacade.queryBusinessOutInfoNew(businessReceiveRefundDto, PageUtil.begin(1, 99999), 99999);
				List<BusinessReceiveRefund> businessChangeList = responseList.getRows();
				List<Map<String, String>> listMap = businessOutNewList(businessChangeList, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList,headerNumList, name, response);
			}
		} catch (Exception e) {
			logger.error("退换列表导出异常:",e);
		}
	}

	/**
	 * 组装导出换房数据
	 */
	private List<Map<String, String>> businessOutNewList(List<BusinessReceiveRefund> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {


			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;
				BusinessReceiveRefund data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
                map.put(head[n++]+"_"+i, (data.getCustomerName() != null ?data.getCustomerName():"")+";"+(data.getCustomerFamilyName() != null ?data.getCustomerFamilyName():"")); //
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():""); //
				map.put(head[n++]+"_"+i, data.getUserName() != null ?data.getUserName():""); //
				map.put(head[n++]+"_"+i, data.getCreateTime() != null ?data.getCreateTime().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getAuditStatus() != null ?data.getAuditStatus():""); //
				map.put(head[n++]+"_"+i, data.getCheckDat() != null ?data.getCheckDat().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getBusinessNype() != null ?data.getBusinessNype():""); //
				map.put(head[n++]+"_"+i, data.getContactType() != null ?data.getContactType():""); //
				map.put(head[n++]+"_"+i, data.getDateTime() != null ?data.getDateTime().substring(0,10):""); //

				map.put(head[n++]+"_"+i, data.getCustomerOrigin() != null ?data.getCustomerOrigin():""); //

				map.put(head[n++]+"_"+i, data.getBuildingArea() != null ?data.getBuildingArea():""); //
				map.put(head[n++]+"_"+i, data.getTotalAmount() != null ?data.getTotalAmount():""); //
				map.put(head[n++]+"_"+i, data.getBuildingPrice() != null ?data.getBuildingPrice():""); //
				map.put(head[n++]+"_"+i, data.getConversionPrice() != null ?data.getConversionPrice():""); //
				map.put(head[n++]+"_"+i, data.getSubscribeAmount() != null ?data.getSubscribeAmount():""); //
				map.put(head[n++]+"_"+i, data.getReceivablePayment() != null ?data.getReceivablePayment():""); //
				map.put(head[n++]+"_"+i, data.getBackPayment() != null ?data.getBackPayment():""); //
				map.put(head[n++]+"_"+i, data.getAgentName() != null ?data.getAgentName():""); //
				map.put(head[n++]+"_"+i, data.getReasonType() != null ?data.getReasonType():""); //
				map.put(head[n++]+"_"+i, data.getReason() != null ?data.getReason():""); //

				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出签约回款提醒数据错误：{}",e);
		}
		return listMap;
	}
	/**
	 *
	 * getModelByPage:(查询列表数据). <br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "queryPaymentStagesBaseInfo")
	public @ResponseBody AjaxRes queryPaymentStagesBaseInfo(HttpServletRequest request,Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:list"))){
				User user = ShiroUtil.getCurrentUser();

                PaymentStagesDto paymentStagesDto = new PaymentStagesDto();

                paymentStagesDto.setMerchantId(user.getMerchantId());
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                paymentStagesDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    paymentStagesDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    paymentStagesDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				if(paymentStagesDto.getProjectId() ==null){
					paymentStagesDto.setProjectId(153l);
				}
//				paymentStagesDto.setProjectId(153l);
				paymentStagesDto.setExport(false);
				Page<PaymentStages> response = businessChangeServiceFacade.queryPaymentStagesBaseInfo(paymentStagesDto, PageUtil.begin(pageNum, pageSize), pageSize);
				List<PaymentStages> psLs = response.getRows();
				if(psLs == null){
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
					return ar;
				}
				List<String> list = new ArrayList<String>();
				for(PaymentStages ps:psLs){
					list.add(ps.getId().toString());
				}
				//获取垫付首付
				List<PaymentStages> haveLs = businessChangeServiceFacade.queryPaymentStagesAdvanceHave(list);

				List<PaymentStages> needLs = businessChangeServiceFacade.queryPaymentStagesAdvanceNeed(list);

				List<PaymentStages> detailLs = businessChangeServiceFacade.queryPaymentStagesDetail(list);
				if(psLs != null && psLs.size()>0){
					for(PaymentStages ps:psLs){

                        if(StringUtils.isNotEmpty(ps.getPaymentMethod())){
                            ps.setPaymentMethod(PaymentMethodEnum.getByNo(ps.getPaymentMethod()).getDes());
                        }
						if (haveLs != null && haveLs.size()>0){
							for(PaymentStages d:haveLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								ps.setTotalHaveAdvance(d.getTotalHave());
								break;
							}
						}
						if (needLs != null && needLs.size()>0){
							for(PaymentStages d:needLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								ps.setTotalNeedAdvance(d.getTotalNeed());
								break;
							}
						}

                        if (detailLs != null && detailLs.size()>0){
							for(PaymentStages d:detailLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								if(d.getReceivablesFunds().indexOf("一期") >= 0){
									ps.setNeedTime1(d.getSignDate());
									ps.setNeedAmt1(d.getTotalNeed());
									ps.setHaveAmt1(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("二期") >= 0){
									ps.setNeedTime2(d.getSignDate());
									ps.setNeedAmt2(d.getTotalNeed());
									ps.setHaveAmt2(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("三期") >= 0){
									ps.setNeedTime3(d.getSignDate());
									ps.setNeedAmt3(d.getTotalNeed());
									ps.setHaveAmt3(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("四期") >= 0){
									ps.setNeedTime4(d.getSignDate());
									ps.setNeedAmt4(d.getTotalNeed());
									ps.setHaveAmt4(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("五期") >= 0){
									ps.setNeedTime5(d.getSignDate());
									ps.setNeedAmt5(d.getTotalNeed());
									ps.setHaveAmt5(d.getTotalHave());
								}
							}
						}

					}
				}
                response.setPageNumber(pageNum);
                ar.setSucceed(response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("退房列表查询异常:",e);
		}
		return ar;
	}

	/*@RequestMapping(value = "queryPaymentStagesDetail")
	public @ResponseBody List<PaymentStages> queryPaymentStagesDetail(PaymentStagesDto paymentStagesDto){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:list"))){
				User user = ShiroUtil.getCurrentUser();
				paymentStagesDto.setMerchantId(user.getMerchantId());
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				paymentStagesDto.setExport(false);
				List<PaymentStages> response = businessChangeServiceFacade.queryPaymentStagesDetail(paymentStagesDto);
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("退房列表查询异常:",e);
		}
		return new ArrayList<>();
	}*/

	@RequestMapping(value = "paymentStagesExport")
	public void paymentStagesExport(HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
//				String jsonStr=URLDecoder.decode(value,"utf-8");
//				PaymentStagesDto paymentStagesDto = JSONObject.parseObject(jsonStr,PaymentStagesDto.class);
//				PaymentStagesDto paymentStagesDto = new PaymentStagesDto();
						User user = ShiroUtil.getCurrentUser();
                PaymentStagesDto paymentStagesDto = new PaymentStagesDto();
                String premisesId = request.getParameter("premisesId");
                String strTime =   request.getParameter("strTime");
                String endTime =   request.getParameter("endTime");
                paymentStagesDto.setPremisesId(premisesId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (strTime != "" && strTime != null){
                    paymentStagesDto.setStrTime(sdf.parse(strTime+" 00:00:00"));
                }
                if (endTime != "" && endTime != null){
                    paymentStagesDto.setEndTime(sdf.parse(endTime+" 23:59:59"));
                }

				paymentStagesDto.setMerchantId(user.getMerchantId());
				if(paymentStagesDto.getProjectId() ==null){
					paymentStagesDto.setProjectId(153l);
				}
//				businessReceiveRefundDto.setPermissionUserId(user.getId());
				paymentStagesDto.setExport(true);
				String[] name = new String[]{"首付分期"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"项目名称","分期","房间","业态","房号","合同类型","付款方式","客户姓名","置业顾问","销售团队","签约日期","网签日期"
						,"分期款合计","分期款欠款","垫付首期合计","垫付首期欠款","第一笔应收时间","第一笔应收金额","第一笔欠款","第二笔应收时间","第二笔应收金额"
						,"第二笔欠款","第三笔应收时间","第三笔应收金额","第三笔欠款","第四笔应收时间","第四笔应收金额","第四笔欠款"
						,"第五笔应收时间","第五笔应收金额","第五笔欠款"

				};
				headerList.add(header);

				List<String[]> headerNumList = new ArrayList<String[]>();
				String[] headerNum = new String[]{

						"分期款合计","分期款欠款","第一笔应收金额","第一笔欠款","第二笔应收金额","垫付首期合计","垫付首期欠款"
						,"第二笔欠款","第三笔应收金额","第三笔欠款","第四笔应收金额","第四笔欠款"
						,"第五笔应收金额","第五笔欠款"

				};
				headerNumList.add(headerNum);
				Page<PaymentStages> responseList = businessChangeServiceFacade.queryPaymentStagesBaseInfo(paymentStagesDto, PageUtil.begin(1, 99999), 99999);
				List<PaymentStages> psLs = responseList.getRows();
				List<List<String >> dataList = new ArrayList<List<String >>();

				List<String> temList = new ArrayList<String>();
				for(PaymentStages ps:psLs){
					if(temList.size()>1500){
						dataList.add(temList);
						temList = new ArrayList<String>();
					}else{
						temList.add(ps.getId().toString());
					}

				}
				if(temList.size() >0 ){
					dataList.add(temList);
				}
//				PaymentStagesDto tem = new PaymentStagesDto();
//				tem.setList(temList);
//				Map<String,PaymentStages> dataLMap = new HashMap<String,PaymentStages>();
				List<PaymentStages> detailLs = new ArrayList<PaymentStages>();
				for(List<String > data : dataList){
					List<PaymentStages> ls = businessChangeServiceFacade.queryPaymentStagesDetail(data);
					if(ls != null){
						detailLs.addAll(ls);
					}

				}

				//获取垫付首付
				List<PaymentStages> haveLs = new ArrayList<PaymentStages>();
				for(List<String > data : dataList){
					List<PaymentStages> ls = businessChangeServiceFacade.queryPaymentStagesAdvanceHave(data);
					if(ls != null){
						haveLs.addAll(ls);
					}

				}

				List<PaymentStages> needLs = new ArrayList<PaymentStages>();
				for(List<String > data : dataList){
					List<PaymentStages> ls = businessChangeServiceFacade.queryPaymentStagesAdvanceNeed(data);
					if(ls != null){
						needLs.addAll(ls);
					}

				}


				if(psLs != null && psLs.size()>0){
					for(PaymentStages ps:psLs){

						if(StringUtils.isNotEmpty(ps.getPaymentMethod())){
							ps.setPaymentMethod(PaymentMethodEnum.getByNo(ps.getPaymentMethod()).getDes());
						}
						if (haveLs != null && haveLs.size()>0){
							for(PaymentStages d:haveLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								ps.setTotalHaveAdvance(d.getTotalHave());
								break;
							}
						}
						if (needLs != null && needLs.size()>0){
							for(PaymentStages d:needLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								ps.setTotalNeedAdvance(d.getTotalNeed());
								break;
							}
						}

						if (detailLs != null && detailLs.size()>0){
							for(PaymentStages d:detailLs){

								if(ps.getId().longValue() != d.getId().longValue() ){
									continue;
								}

								if(d.getReceivablesFunds().indexOf("一期") >= 0){
									ps.setNeedTime1(d.getSignDate());
									ps.setNeedAmt1(d.getTotalNeed());
									ps.setHaveAmt1(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("二期") >= 0){
									ps.setNeedTime2(d.getSignDate());
									ps.setNeedAmt2(d.getTotalNeed());
									ps.setHaveAmt2(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("三期") >= 0){
									ps.setNeedTime3(d.getSignDate());
									ps.setNeedAmt3(d.getTotalNeed());
									ps.setHaveAmt3(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("四期") >= 0){
									ps.setNeedTime4(d.getSignDate());
									ps.setNeedAmt4(d.getTotalNeed());
									ps.setHaveAmt4(d.getTotalHave());
								}else if(d.getReceivablesFunds().indexOf("五期") >= 0){
									ps.setNeedTime5(d.getSignDate());
									ps.setNeedAmt5(d.getTotalNeed());
									ps.setHaveAmt5(d.getTotalHave());
								}
							}
						}

					}
				}

				List<Map<String, String>> listMap = paymentStagesList(psLs, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList,headerNumList, name, response);
			}
		} catch (Exception e) {
			logger.error("退换列表导出异常:",e);
		}
	}

	/**
	 * 组装导出换房数据
	 */
	private List<Map<String, String>> paymentStagesList(List<PaymentStages> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;

				PaymentStages data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();

/*				if(StringUtils.isNotEmpty(data.getPaymentMethod())){
				    data.setPaymentMethod(PaymentMethodEnum.getByNo(data.getPaymentMethod()).getDes());
                }*/
				map.put(head[n++]+"_"+i, data.getProjectName() != null ?data.getProjectName():""); //
                map.put(head[n++]+"_"+i, data.getPremisesName() != null ?data.getPremisesName():""); //
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():""); //
				map.put(head[n++]+"_"+i, data.getIndustMark() != null ?data.getIndustMark():""); //
				map.put(head[n++]+"_"+i, data.getRoomName() != null ? data.getBuildingName() + "-" + data.getRoomName():""); //
				map.put(head[n++]+"_"+i, data.getContactType() != null ?data.getContactType():""); //
				map.put(head[n++]+"_"+i, data.getPaymentMethod() != null ?("首付分期-"+data.getPaymentMethod()):""); //
				map.put(head[n++]+"_"+i, (data.getCustomerName() != null ?data.getCustomerName():"")+";"+(data.getCustomerFamilyName() != null ?data.getCustomerFamilyName():"")); //
				map.put(head[n++]+"_"+i, data.getAgentName() != null ?data.getAgentName():""); //
				map.put(head[n++]+"_"+i, data.getGroupName() != null ?data.getGroupName():""); //
				map.put(head[n++]+"_"+i, data.getSignDate() != null ?data.getSignDate().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getSignDate() != null ?data.getSignDate().substring(0,10):""); //

				map.put(head[n++]+"_"+i, data.getTotalNeed() != null ?data.getTotalNeed().toString():""); //
				map.put(head[n++]+"_"+i, data.getTotalHave() != null ?data.getTotalNeed().subtract(data.getTotalHave()).toString():""); //

				map.put(head[n++]+"_"+i, data.getTotalNeedAdvance() != null ?data.getTotalNeedAdvance().toString():""); //
				map.put(head[n++]+"_"+i, data.getTotalHaveAdvance() != null ?data.getTotalNeedAdvance().subtract(data.getTotalHaveAdvance()).toString():""); //

				map.put(head[n++]+"_"+i, data.getNeedTime1() != null ?data.getNeedTime1().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getNeedAmt1().toString()); //
				map.put(head[n++]+"_"+i, data.getHaveAmt1().toString()); //

				map.put(head[n++]+"_"+i, data.getNeedTime2() != null ?data.getNeedTime2().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getNeedAmt2().toString()); //
				map.put(head[n++]+"_"+i, data.getHaveAmt2().toString()); //

				map.put(head[n++]+"_"+i, data.getNeedTime3() != null ?data.getNeedTime3().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getNeedAmt3().toString()); //
				map.put(head[n++]+"_"+i, data.getHaveAmt3().toString()); //

				map.put(head[n++]+"_"+i, data.getNeedTime4() != null ?data.getNeedTime4().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getNeedAmt4().toString()); //
				map.put(head[n++]+"_"+i, data.getHaveAmt4().toString()); //

				map.put(head[n++]+"_"+i, data.getNeedTime5() != null ?data.getNeedTime5().substring(0,10):""); //
				map.put(head[n++]+"_"+i, data.getNeedAmt5().toString()); //
				map.put(head[n++]+"_"+i, data.getHaveAmt5().toString()); //





				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出签约回款提醒数据错误：{}",e);
		}
		return listMap;
	}

	@RequestMapping(value="toAuditAccountList")
	public String toAuditAccountList(ModelMap map){
		ProjectPremisesDto premisesDto = new ProjectPremisesDto();
		premisesDto.setProjectId(153L);
		ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
		map.put("premisesList",dataList.getEntity());
		return "/report/auditAccountReport";
	}

	@RequestMapping(value = "queryAuditAccountInfo")
	@ResponseBody
	public AjaxRes queryAuditAccountInfo(PaymentStagesDto paymentStagesDto, Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			paymentStagesDto.setMerchantId(user.getMerchantId());
			if(paymentStagesDto.getProjectId() ==null){
				paymentStagesDto.setProjectId(153L);
			}
			paymentStagesDto.setExport(false);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
				paymentStagesDto.setStrTime(sdf.parse(paymentStagesDto.getCheckDateBefore()+" 00:00:00"));
			}
			if (StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
				paymentStagesDto.setEndTime(sdf.parse(paymentStagesDto.getCheckDateAfter()+" 23:59:59"));
			}
			Page<PaymentStages> response = businessChangeServiceFacade.queryAuditAccountInfo(paymentStagesDto, PageUtil.begin(pageNum, pageSize), pageSize);
			List<PaymentStages> psLs = response.getRows();
			if(psLs == null){
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
				return ar;
			}

			auditAccountInfoData(psLs, false);

			if(response.getSuccess()&&response.getRows()!=null){
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
				return ar;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("审算台账报表查询异常:",e);
		}
		return ar;
	}

	@RequestMapping(value = "auditAccountInfoExport")
	public void auditAccountInfoExport(PaymentStagesDto paymentStagesDto,HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
				User user = ShiroUtil.getCurrentUser();
				paymentStagesDto.setMerchantId(user.getMerchantId());
				if(paymentStagesDto.getProjectId() ==null){
					paymentStagesDto.setProjectId(153L);
				}
				paymentStagesDto.setExport(true);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if (StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
					paymentStagesDto.setStrTime(sdf.parse(paymentStagesDto.getCheckDateBefore()+" 00:00:00"));
				}
				if (StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
					paymentStagesDto.setEndTime(sdf.parse(paymentStagesDto.getCheckDateAfter()+" 23:59:59"));
				}
				String[] name = new String[]{"审算台账"};
				List<String[]> headerList = new ArrayList<>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"项目名称","认购日期","签约状态","签约日期","网签日期","合同编号","房产坐落","楼栋","单元","房号"
						,"业态","买受人","共有人","买受人证件号码","共有人证件号码","联系电话","通讯地址","预售面积","实测面积","实收定金"
						,"成交单价","成交总价","成交面积","折扣方案","付款方式","实收房款（包含面积差）","应收首期","实收首期","欠收首期","分期1时间"
						,"分期1金额","分期1余额","分期2时间","分期2金额","分期2余额","分期3时间","分期3金额","分期3余额","分期4时间","分期4金额"
						,"分期4余额","分期5时间","分期5金额","分期5余额","分期6时间","分期6金额","分期6余额","应收按揭","实收按揭","按揭银行"
						,"按揭到账日期","欠收按揭","期间首付回款（不含补差款）","期间按揭回款","累计回款（不含补差款）","建筑面积差","应补退面积差价","实补退面积差价","代收维修基金","置业顾问"
						,"媒体大类","媒体子类","备注"
				};
				headerList.add(header);
				List<String[]> numberList = new ArrayList<>();
				String[] numberHeader = new String[]{
						"预售面积","实测面积","实收定金","成交单价","成交总价","实收房款（包含面积差）","应收首期","实收首期","欠收首期"
						,"分期1金额","分期1余额","分期2金额","分期2余额","分期3金额","分期3余额","分期4金额"
						,"分期4余额","分期5金额","分期5余额","分期6金额","分期6余额","应收按揭","实收按揭"
						,"欠收按揭","期间首付回款（不含补差款）","期间按揭回款","累计回款（不含补差款）","建筑面积差","应补退面积差价","实补退面积差价","代收维修基金"
				};
				numberList.add(numberHeader);

				paymentStagesDto.setExportFlag("1");
				Page<PaymentStages> pageResponse = businessChangeServiceFacade.queryAuditAccountInfo(paymentStagesDto, PageUtil.begin(1, 10), 10);
				List<PaymentStages> psLs = pageResponse.getRows();

				auditAccountInfoData(psLs, true);

				List<Map<String, String>> listMap = auditAccountInfoList(psLs, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList, numberList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("审算台账导出异常:",e);
		}
	}


	/**
	 * 组装导出审算台账数据
	 */
	private List<Map<String, String>> auditAccountInfoList(List<PaymentStages> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;
				PaymentStages data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[n++]+"_"+i, data.getProjectName() != null ?data.getProjectName():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSubscribeDate())?data.getSubscribeDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getNetSign() != null ?data.getNetSign():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSignDate())?data.getSignDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSignDate())?data.getSignDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getSignCode() != null ?data.getSignCode():"");
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():"");
				map.put(head[n++]+"_"+i, data.getBuildingName() != null ?data.getBuildingName():"");
				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, data.getRoomName() != null ?data.getRoomName():"");

				//11
				map.put(head[n++]+"_"+i, data.getIndustMark() != null ?data.getIndustMark():"");
				map.put(head[n++]+"_"+i, data.getCustomerName() != null ?data.getCustomerName():"");
				map.put(head[n++]+"_"+i, data.getCoownerName() != null ?data.getCoownerName():"");

				map.put(head[n++]+"_"+i, data.getCustomerDocumentNumber() != null ?data.getCustomerDocumentNumber():"");
				map.put(head[n++]+"_"+i, data.getCoownerDocumentNumber() != null ?data.getCoownerDocumentNumber():"");
				map.put(head[n++]+"_"+i, data.getCustomerPhone() != null ?data.getCustomerPhone():"");

				map.put(head[n++]+"_"+i, data.getContractAddress() != null ?data.getContractAddress():"");
				map.put(head[n++]+"_"+i, data.getBuildingArea() != null ?data.getBuildingArea():"");
				map.put(head[n++]+"_"+i, data.getBillingArea() != null ?data.getBillingArea():"");

				map.put(head[n++]+"_"+i, data.getSubscribeAmount() != null ?data.getSubscribeAmount():"");

				//21
				map.put(head[n++]+"_"+i, data.getSignPrice() != null ?data.getSignPrice():"");
				map.put(head[n++]+"_"+i, data.getSignAmount() != null ?data.getSignAmount():"");
				map.put(head[n++]+"_"+i, data.getCalculateArea() != null ?data.getCalculateArea():"");
				map.put(head[n++]+"_"+i, data.getDiscountNote() != null ?data.getDiscountNote():"");
				map.put(head[n++]+"_"+i, data.getPaymentMethod() != null ?data.getPaymentMethod():"");
				map.put(head[n++]+"_"+i, data.getHousingFund() != null ?data.getHousingFund():"");
				map.put(head[n++]+"_"+i, data.getNeedFirstFund() != null ?data.getNeedFirstFund():"");
				map.put(head[n++]+"_"+i, data.getHaveFirstFund() != null ?data.getHaveFirstFund():"");
				map.put(head[n++]+"_"+i, data.getBalanceFirstFund() != null ?data.getBalanceFirstFund():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime1())?data.getNeedTime1().substring(0,10):"");

				//31
				map.put(head[n++]+"_"+i, data.getNeedAmt1().toString());
				map.put(head[n++]+"_"+i, data.getBalanceAmt1().toString());

				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime2())?data.getNeedTime2().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getNeedAmt2().toString());
				map.put(head[n++]+"_"+i, data.getBalanceAmt2().toString());

				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime3())?data.getNeedTime3().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getNeedAmt3().toString());
				map.put(head[n++]+"_"+i, data.getBalanceAmt3().toString());

				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime4())?data.getNeedTime4().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getNeedAmt4().toString());

				//41
				map.put(head[n++]+"_"+i, data.getBalanceAmt4().toString());

				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime5())?data.getNeedTime5().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getNeedAmt5().toString());
				map.put(head[n++]+"_"+i, data.getBalanceAmt5().toString());

				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, "");

				map.put(head[n++]+"_"+i, data.getNeedBankFund() != null ?data.getNeedBankFund():"");
				map.put(head[n++]+"_"+i, data.getHaveBankFund() != null ?data.getHaveBankFund():"");
				map.put(head[n++]+"_"+i, data.getBankName() != null ?data.getBankName():"");

				//51
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getHaveBankFundDate())?data.getHaveBankFundDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getBalanceBankFund() != null ?data.getBalanceBankFund():"");
				map.put(head[n++]+"_"+i, data.getPeriodFirstFund() != null ?data.getPeriodFirstFund():"");
				map.put(head[n++]+"_"+i, data.getPeriodBankFund() != null ?data.getPeriodBankFund():"");
				map.put(head[n++]+"_"+i, data.getPeriodTotalFund() != null ?data.getPeriodTotalFund():"");
				map.put(head[n++]+"_"+i, "0.00");
				map.put(head[n++]+"_"+i, "0.00");
				map.put(head[n++]+"_"+i, "0.00");
				map.put(head[n++]+"_"+i, "0.00");
				map.put(head[n++]+"_"+i, data.getUserName() != null ?data.getUserName():"");

				//61
				map.put(head[n++]+"_"+i, data.getInformedWay() != null ?data.getInformedWay():"");
				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, "");

				listMap.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("组装导出审算台账数据错误：{}",e);
		}
		return listMap;
	}

	private void auditAccountInfoData(List<PaymentStages> psLs, boolean exportFlag){
		for(PaymentStages paymentStages : psLs){
			String combinedName = paymentStages.getCombinedName();
			if(combinedName.indexOf("-->")>-1) {
				combinedName = combinedName.replaceAll("-->1-->", "-->");
				String[] roomNameArray = combinedName.split("-->");
				paymentStages.setProjectName(roomNameArray[0] + "-" + roomNameArray[1]);
				paymentStages.setCombinedName(combinedName.replaceAll("-->", "-"));
				paymentStages.setBuildingName(roomNameArray[2]);
				paymentStages.setRoomName(roomNameArray[roomNameArray.length - 1]);
			}

			if(StringUtils.isNotBlank(paymentStages.getPaymentMethod())) {
				String paymentMethod = PaymentMethodEnum.getByNo(paymentStages.getPaymentMethod()).getDes();
				paymentStages.setPaymentMethod("2".equals(paymentStages.getDecorationPaymentMethod()) ? "首付分期【" + paymentMethod + "】" : paymentMethod);
			}

			String bankName = StringUtils.isBlank(paymentStages.getBankCode())?"":BankNameEnum.getByNo(paymentStages.getBankCode()).getDes();
			paymentStages.setBankName(bankName);

			paymentStages.setBillingArea("0.00");

			BigDecimal balanceFirstFund = new BigDecimal(paymentStages.getNeedFirstFund()==null?"0":paymentStages.getNeedFirstFund()).subtract(new BigDecimal(paymentStages.getHaveFirstFund()==null?"0":paymentStages.getHaveFirstFund()));
			paymentStages.setBalanceFirstFund(balanceFirstFund.toString());
			BigDecimal balanceBankFund = new BigDecimal(paymentStages.getNeedBankFund()==null?"0":paymentStages.getNeedBankFund()).subtract(new BigDecimal(paymentStages.getHaveBankFund()==null?"0":paymentStages.getHaveBankFund()));
			paymentStages.setBalanceBankFund(balanceBankFund.toString());

			paymentStages.setBalanceAmt1(paymentStages.getNeedAmt1().subtract(paymentStages.getBalanceAmt1()));
			paymentStages.setBalanceAmt2(paymentStages.getNeedAmt2().subtract(paymentStages.getBalanceAmt2()));
			paymentStages.setBalanceAmt3(paymentStages.getNeedAmt3().subtract(paymentStages.getBalanceAmt3()));
			paymentStages.setBalanceAmt4(paymentStages.getNeedAmt4().subtract(paymentStages.getBalanceAmt4()));
			paymentStages.setBalanceAmt5(paymentStages.getNeedAmt5().subtract(paymentStages.getBalanceAmt5()));

			//客户名称
			if(!exportFlag) {
				if(paymentStages.getSubscribeId()!=null || paymentStages.getSignedId()!=null) {
					FamilyMemberDto fmd = new FamilyMemberDto();
					fmd.setMemberType(paymentStages.getSignedId()==null?"3":"4");
					fmd.setBuyId(paymentStages.getSignedId()==null?paymentStages.getSubscribeId():paymentStages.getSignedId());
					ResponseList<FamilyMember> familyMemberResponseList = familyMemberServiceFacade.findByDto(fmd);

					if (familyMemberResponseList.getEntity() != null) {
						StringBuffer coownerName = new StringBuffer();
						StringBuffer coownerDocumentNumber = new StringBuffer();
						for(FamilyMember familyMember : familyMemberResponseList.getEntity()){
							coownerName.append(familyMember.getMemberName()+";");
							coownerDocumentNumber.append(familyMember.getDocumentNumber()+";");
						}
						if(coownerName.length()>0){
							coownerName.deleteCharAt(coownerName.length()-1);
						}
						if(coownerDocumentNumber.length()>0){
							coownerDocumentNumber.deleteCharAt(coownerDocumentNumber.length()-1);
						}
						paymentStages.setCoownerName(coownerName.toString());
						paymentStages.setCoownerDocumentNumber(coownerDocumentNumber.toString());
					}
				}
			}else{
				if(StringUtils.isNotBlank(paymentStages.getCustomerFamilyName())) {
					paymentStages.setCoownerName(paymentStages.getCustomerFamilyName());
				}
			}
		}
	}

	@RequestMapping(value="toReceiptDetailList")
	public String toReceiptDetailList(ModelMap map){
		ProjectPremisesDto premisesDto = new ProjectPremisesDto();
		premisesDto.setProjectId(153L);
		ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
		map.put("premisesList",dataList.getEntity());
		return "/report/receiptDetailReport";
	}

	@RequestMapping(value = "queryReceiptDetailInfo")
	@ResponseBody
	public AjaxRes queryReceiptDetailInfo(PaymentStagesDto paymentStagesDto, Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			paymentStagesDto.setMerchantId(user.getMerchantId());
			if(paymentStagesDto.getProjectId() ==null){
				paymentStagesDto.setProjectId(153L);
			}
			paymentStagesDto.setExport(false);

			Project project = projectServiceFacade.findById(153L).getEntity();

			HaveReceiveRefundInfoDto haveReceiveRefundDto = new HaveReceiveRefundInfoDto();
			haveReceiveRefundDto.setDelFlag("0");
			haveReceiveRefundDto.setAccessCode(project.getAccessCode());
			if(StringUtils.isNotBlank(paymentStagesDto.getPremisesId())){
				haveReceiveRefundDto.setPremisesId(paymentStagesDto.getPremisesId());
			}
			if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
				haveReceiveRefundDto.setStatementDateBefore(DateUtils.parseDate(paymentStagesDto.getCheckDateBefore()+" 00:00:00", DateUtils.parsePatterns[3]));
			}
			if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
				haveReceiveRefundDto.setStatementDateAfter(DateUtils.parseDate(paymentStagesDto.getCheckDateAfter()+" 23:59:59", DateUtils.parsePatterns[3]));
			}
			Page<HaveReceiveRefundInfo> response = haveReceiveRefundServiceFacade.findPageByDtoReport(haveReceiveRefundDto, PageUtil.begin(pageNum, pageSize), pageSize);
			List<HaveReceiveRefundInfo> psLs = response.getRows();
			if(psLs == null){
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
				return ar;
			}

			List<PaymentStages> resultList = new ArrayList<>();
			receiptDetailInfoData(psLs, resultList, false);

			if(response.getSuccess()&&response.getRows()!=null){
				response.setPageNumber(pageNum);
				Page<PaymentStages> detailResponse = new Page<>();
				detailResponse.setRows(resultList);
				detailResponse.setPageNumber(response.getPageNumber());
				detailResponse.setTotal(response.getTotal());
				detailResponse.setPageSize(response.getPageSize());
				ar.setSucceed(detailResponse);
				return ar;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("收款明细表查询异常:",e);
		}
		return ar;
	}

	@RequestMapping(value = "receiptDetailInfoExport")
	public void receiptDetailInfoExport(PaymentStagesDto paymentStagesDto,HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
				User user = ShiroUtil.getCurrentUser();
				paymentStagesDto.setMerchantId(user.getMerchantId());
				if(paymentStagesDto.getProjectId() ==null){
					paymentStagesDto.setProjectId(153L);
				}
				paymentStagesDto.setExport(true);
				String[] name = new String[]{"收款明细"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<String[]> numberList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"项目","楼栋","单元","房间","面积","成交总价","房号","VIP号","房间全称","业态"
						,"认购日期","签约日期","收退款日期","单据类型","票据类型","票据编号","交款人","交款客户信息","交易类型","款项类型"
						,"款项名称","金额","支付方式","入账银行","备注"
				};
				headerList.add(header);
				String[] numberHeader = new String[]{
						"面积","成交总价","金额"
				};
				numberList.add(numberHeader);

				Project project = projectServiceFacade.findById(paymentStagesDto.getProjectId()).getEntity();

				HaveReceiveRefundInfoDto haveReceiveRefundDto = new HaveReceiveRefundInfoDto();
				haveReceiveRefundDto.setAccessCode(project.getAccessCode());
				haveReceiveRefundDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				if(StringUtils.isNotBlank(paymentStagesDto.getPremisesId())){
					haveReceiveRefundDto.setPremisesId(paymentStagesDto.getPremisesId());
				}
				if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
					haveReceiveRefundDto.setStatementDateBefore(DateUtils.parseDate(paymentStagesDto.getCheckDateBefore()+" 00:00:00", DateUtils.parsePatterns[3]));
				}
				if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
					haveReceiveRefundDto.setStatementDateAfter(DateUtils.parseDate(paymentStagesDto.getCheckDateAfter()+" 23:59:59", DateUtils.parsePatterns[3]));
				}
				haveReceiveRefundDto.setIsExport("1");
				Page<HaveReceiveRefundInfo> haveResponse = haveReceiveRefundServiceFacade.findPageByDtoReport(haveReceiveRefundDto, PageUtil.begin(1, 10), 10);
				List<HaveReceiveRefundInfo> psLs = haveResponse.getRows();

				List<PaymentStages> resultList = new ArrayList<>();
				if(psLs!=null) {
					receiptDetailInfoData(psLs, resultList, true);
				}

				List<Map<String, String>> listMap = receiptDetailInfoList(resultList, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList, numberList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("收款明细导出异常:",e);
		}
	}

	private void receiptDetailInfoData(List<HaveReceiveRefundInfo> haveReceiveRefundList, List<PaymentStages> resultList, boolean exportFlag){
		for(HaveReceiveRefundInfo haveReceiveRefund : haveReceiveRefundList){
			PaymentStages paymentStages = new PaymentStages();

			paymentStages.setPayerName(haveReceiveRefund.getPayerName());
			paymentStages.setHaveBankFundDate(DateUtils.dateToString(haveReceiveRefund.getStatementDate(),DateUtils.parsePatterns[1]));
			paymentStages.setBillType(StringUtils.isNotBlank(haveReceiveRefund.getBillCode())?"收据":"无票据");
			paymentStages.setBillCode(haveReceiveRefund.getBillCode());
			if(StringUtils.isNotBlank(haveReceiveRefund.getBusinessTypeName())){
				paymentStages.setBusinessType(haveReceiveRefund.getBusinessTypeName());
			}else {
				paymentStages.setBusinessType("交易");
			}
			paymentStages.setRealAmount(("1".equals(haveReceiveRefund.getDocType())?"-":"")+haveReceiveRefund.getRealAmount().toString());
			paymentStages.setStatementType(haveReceiveRefund.getStatementType()!=null?StatementTypeEnum.getByNo(haveReceiveRefund.getStatementType()+"").getDes():"");
			String bankName = StringUtils.isBlank(haveReceiveRefund.getBankCode())?"":BankNameEnum.getByNo(haveReceiveRefund.getBankCode()).getDes();
			paymentStages.setBankName(bankName);
			paymentStages.setHousingFundType(HousingFundTypeEnum.getByNo(haveReceiveRefund.getHousingFundType()).getDes());
			if(StringUtils.isNotBlank(haveReceiveRefund.getGrayType())) {
				paymentStages.setPaymentType(haveReceiveRefund.getGrayType());
			}else{
				if (HousingFundTypeEnum.FUNDTYPE_1.getNo().equals(haveReceiveRefund.getHousingFundType())) {
					paymentStages.setPaymentType("其它");
				} else if (HousingFundTypeEnum.FUNDTYPE_7.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_11.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_18.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_19.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_28.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_36.getNo().equals(haveReceiveRefund.getHousingFundType())
						|| HousingFundTypeEnum.FUNDTYPE_37.getNo().equals(haveReceiveRefund.getHousingFundType())) {
					paymentStages.setPaymentType("贷款类房款");
				} else {
					paymentStages.setPaymentType("非贷款类房款");
				}
			}
			paymentStages.setCustomerName(haveReceiveRefund.getCustomer_name());
			paymentStages.setIndustMark(StringUtils.isNotBlank(haveReceiveRefund.getIndustMark())?haveReceiveRefund.getIndustMark():"");
			paymentStages.setSignCode(haveReceiveRefund.getRelationCode());
			String combinedName = haveReceiveRefund.getCombined_name().replaceAll("-->1-->", "-->");
			if(combinedName.indexOf("-->")>-1) {
				combinedName = combinedName.replaceAll("-->1-->", "-->");
				String[] roomNameArray = combinedName.split("-->");
				paymentStages.setProjectName(roomNameArray[0] + "-" + roomNameArray[1]);
				paymentStages.setCombinedName(combinedName.replaceAll("-->", "-"));
				paymentStages.setBuildingName(roomNameArray[2]);
				paymentStages.setRoomName(roomNameArray[roomNameArray.length - 1]);
				paymentStages.setGroupName(roomNameArray[2] + "-" + roomNameArray[roomNameArray.length - 1]);
			}else{
				paymentStages.setProjectName(combinedName);
				paymentStages.setCombinedName(combinedName);
				paymentStages.setBuildingName(combinedName);
				paymentStages.setRoomName(combinedName);
				paymentStages.setGroupName(combinedName);
			}

			//共有人
			if(exportFlag) {
				paymentStages.setSignDate(haveReceiveRefund.getSignDate() != null ? DateUtils.dateToString(haveReceiveRefund.getSignDate(), DateUtils.parsePatterns[1]) : "");
				paymentStages.setSubscribeDate(haveReceiveRefund.getSubscribeDate() != null ? DateUtils.dateToString(haveReceiveRefund.getSubscribeDate(), DateUtils.parsePatterns[1]) : "");
				paymentStages.setSignAmount(haveReceiveRefund.getTotalPrice() != null ? haveReceiveRefund.getTotalPrice().toString() : "");
				paymentStages.setBuildingArea(haveReceiveRefund.getCalculatArea() != null ? haveReceiveRefund.getCalculatArea() : "");

				if(StringUtils.isNotBlank(haveReceiveRefund.getCustomerFamilyName())){
					paymentStages.setCustomerName(haveReceiveRefund.getCustomer_name()+";"+haveReceiveRefund.getCustomerFamilyName());
				}
			}else{
				if("1".equals(haveReceiveRefund.getReceivablesType())||"2".equals(haveReceiveRefund.getReceivablesType())) {
					FamilyMemberDto fmd = new FamilyMemberDto();
					String memberType = "";
					switch (haveReceiveRefund.getReceivablesType()) {
						case "0":
							memberType = "2";
							break;
						case "1":
							memberType = "3";
							break;
						case "2":
							memberType = "4";
							break;
					}
					fmd.setCustomerId(haveReceiveRefund.getCustomerId());
					fmd.setMemberType(memberType);
					fmd.setBuyId(haveReceiveRefund.getRelationId());
					ResponseList<FamilyMember> familyMemberResponseList = familyMemberServiceFacade.findByDto(fmd);
					if (familyMemberResponseList.getEntity() != null) {
						StringBuffer coownerName = new StringBuffer();
						for (FamilyMember familyMember : familyMemberResponseList.getEntity()) {
							coownerName.append(familyMember.getMemberName() + ";");
						}
						if (coownerName.length() > 0) {
							coownerName.deleteCharAt(coownerName.length() - 1);
							paymentStages.setCustomerName(paymentStages.getCustomerName() + ";" + coownerName.toString());
						}
					}

					if("1".equals(haveReceiveRefund.getReceivablesType())){
						Response<Subscribe> subscribeResponse = subscribeServiceFacade.findById(haveReceiveRefund.getRelationId());
						if(subscribeResponse.getEntity()!=null) {
							Subscribe subscribe = subscribeResponse.getEntity();
							paymentStages.setSubscribeDate(DateUtils.dateToString(subscribe.getSubscribeDate(), DateUtils.parsePatterns[1]));
							paymentStages.setSignAmount(subscribe.getSubscribeAmount().toString());
							paymentStages.setBuildingArea(subscribe.getCalculateArea().toString());

							SignedDto signedDto = new SignedDto();
							signedDto.setCustomerId(subscribe.getCustomerId());
							signedDto.setRoomId(subscribe.getRoomId());
							signedDto.setSubscribeId(subscribe.getId());
							signedDto.setAuditStatus("3");
							signedDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							ResponseList<Signed> signedResponseList = signedServiceFacade.findByDto(signedDto);
							if(signedResponseList.getEntity()!=null){
								Signed signed = signedResponseList.getEntity().get(0);
								paymentStages.setSignDate(signed.getSignDate()!=null?DateUtils.dateToString(signed.getSignDate(), DateUtils.parsePatterns[1]):"");
								paymentStages.setSignAmount(signed.getSignAmount().toString());
								paymentStages.setBuildingArea(signed.getCalculateArea().toString());
							}
						}
					}else if("2".equals(haveReceiveRefund.getReceivablesType())){
						Response<Signed> signedResponse = signedServiceFacade.findById(haveReceiveRefund.getRelationId());
						if(signedResponse.getEntity()!=null) {
							Signed signed = signedResponse.getEntity();
							paymentStages.setSignDate(signed.getSignDate() != null ? DateUtils.dateToString(signed.getSignDate(), DateUtils.parsePatterns[1]) : "");
							paymentStages.setSignAmount(signed.getSignAmount().toString());
							paymentStages.setBuildingArea(signed.getCalculateArea().toString());

							Response<Subscribe> subResponse = subscribeServiceFacade.findById(signed.getSubscribeId());
							if(subResponse.getEntity()!=null) {
								Subscribe subscribe = subResponse.getEntity();
								paymentStages.setSubscribeDate(DateUtils.dateToString(subscribe.getSubscribeDate(), DateUtils.parsePatterns[1]));
							}
						}
					}
				}
			}

			if(StringUtils.isNotBlank(haveReceiveRefund.getDocTypeName())) {
				paymentStages.setReceiptType(haveReceiveRefund.getDocTypeName());
			}else{
				if (BusinessFlagEnum.BUSINESSFLAG_1.getNo().equals(haveReceiveRefund.getBusinessFlag()) || BusinessFlagEnum.BUSINESSFLAG_4.getNo().equals(haveReceiveRefund.getBusinessFlag())) {
					paymentStages.setReceiptType("收款单");
				} else if (BusinessFlagEnum.BUSINESSFLAG_5.getNo().equals(haveReceiveRefund.getBusinessFlag()) || BusinessFlagEnum.BUSINESSFLAG_8.getNo().equals(haveReceiveRefund.getBusinessFlag())) {
					paymentStages.setReceiptType("转账单");
				} else if (BusinessFlagEnum.BUSINESSFLAG_9.getNo().equals(haveReceiveRefund.getBusinessFlag()) || BusinessFlagEnum.BUSINESSFLAG_14.getNo().equals(haveReceiveRefund.getBusinessFlag())
						|| BusinessFlagEnum.BUSINESSFLAG_12.getNo().equals(haveReceiveRefund.getBusinessFlag()) || BusinessFlagEnum.BUSINESSFLAG_13.getNo().equals(haveReceiveRefund.getBusinessFlag())
						|| BusinessFlagEnum.BUSINESSFLAG_15.getNo().equals(haveReceiveRefund.getBusinessFlag()) || BusinessFlagEnum.BUSINESSFLAG_19.getNo().equals(haveReceiveRefund.getBusinessFlag())) {
					paymentStages.setReceiptType("收款单");
				}
			}

			resultList.add(paymentStages);
		}
	}

	/**
	 * 组装导出收款明细数据
	 */
	private List<Map<String, String>> receiptDetailInfoList(List<PaymentStages> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;
				PaymentStages data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[n++]+"_"+i, data.getProjectName() != null ?data.getProjectName():"");
				map.put(head[n++]+"_"+i, data.getBuildingName() != null ?data.getBuildingName():"");
				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, data.getRoomName() != null ?data.getRoomName():"");
				map.put(head[n++]+"_"+i, data.getBuildingArea() != null ?data.getBuildingArea():"");
				map.put(head[n++]+"_"+i, data.getSignAmount() != null ?data.getSignAmount():"");
				map.put(head[n++]+"_"+i, data.getGroupName() != null ?data.getGroupName():"");
				map.put(head[n++]+"_"+i, data.getSignCode() != null ?data.getSignCode():"");
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():"");
				map.put(head[n++]+"_"+i, data.getIndustMark() != null ?data.getIndustMark():"");

				//11
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSubscribeDate())?data.getSubscribeDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSignDate())?data.getSignDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getHaveBankFundDate())?data.getHaveBankFundDate().substring(0,10):"");

				map.put(head[n++]+"_"+i, data.getReceiptType() != null ?data.getReceiptType():"");
				map.put(head[n++]+"_"+i, data.getBillType() != null ?data.getBillType():"");
				map.put(head[n++]+"_"+i, data.getBillCode() != null ?data.getBillCode():"");

				map.put(head[n++]+"_"+i, data.getPayerName() != null ?data.getPayerName():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getCustomerName())?data.getCustomerName():data.getPayerName());
				map.put(head[n++]+"_"+i, data.getBusinessType() != null ?data.getBusinessType():"");

				map.put(head[n++]+"_"+i, data.getPaymentType() != null ?data.getPaymentType():"");

				//21
				map.put(head[n++]+"_"+i, data.getHousingFundType() != null ?data.getHousingFundType():"");
				map.put(head[n++]+"_"+i, data.getRealAmount() != null ?data.getRealAmount():"");
				map.put(head[n++]+"_"+i, data.getStatementType() != null ?data.getStatementType():"");
				map.put(head[n++]+"_"+i, data.getBankName() != null ?data.getBankName():"");
				map.put(head[n++]+"_"+i, "");

				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出收款明细数据错误：{}",e);
		}
		return listMap;
	}

	@RequestMapping(value="toContractDiffList")
	public String toContractDiffList(ModelMap map){
		ProjectPremisesDto premisesDto = new ProjectPremisesDto();
		premisesDto.setProjectId(153L);
		ResponseList<ProjectPremises> dataList = projectPremisesServiceFacade.findByDto(premisesDto);
		map.put("premisesList",dataList.getEntity());
		return "/report/contractDiffReport";
	}

	@RequestMapping(value = "queryContractDiffInfo")
	@ResponseBody
	public AjaxRes queryContractDiffInfo(PaymentStagesDto paymentStagesDto, Integer pageNum, Integer pageSize){
		AjaxRes ar=getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			paymentStagesDto.setMerchantId(user.getMerchantId());
			if(paymentStagesDto.getProjectId() ==null){
				paymentStagesDto.setProjectId(153L);
			}
			paymentStagesDto.setExport(false);

			Project project = projectServiceFacade.findById(paymentStagesDto.getProjectId()).getEntity();

			NeedReceiveRefundInfoDto needReceiveRefundDto = new NeedReceiveRefundInfoDto();
			needReceiveRefundDto.setAccessCode(project.getAccessCode());
			needReceiveRefundDto.setBusinessType("2");
			needReceiveRefundDto.setStatus("1");
			needReceiveRefundDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
				needReceiveRefundDto.setReceivablesDateBefore(DateUtils.parseDate(paymentStagesDto.getCheckDateBefore()+" 00:00:00", DateUtils.parsePatterns[3]));
			}
			if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
				needReceiveRefundDto.setReceivablesDateAfter(DateUtils.parseDate(paymentStagesDto.getCheckDateAfter()+" 23:59:59", DateUtils.parsePatterns[3]));
			}
			Page<NeedReceiveRefundInfo> response = needReceiveRefundServiceFacade.findPageByDtoReport(needReceiveRefundDto, PageUtil.begin(pageNum, pageSize), pageSize);
			List<NeedReceiveRefundInfo> psLs = response.getRows();
			if(psLs == null){
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
				return ar;
			}

			List<PaymentStages> resultList = new ArrayList<>();
			contractDiffData(psLs, resultList, project, false);

			if(response.getSuccess()&&response.getRows()!=null){
				response.setPageNumber(pageNum);
				Page<PaymentStages> detailResponse = new Page<>();
				detailResponse.setRows(resultList);
				detailResponse.setPageNumber(response.getPageNumber());
				detailResponse.setTotal(response.getTotal());
				detailResponse.setPageSize(response.getPageSize());
				ar.setSucceed(detailResponse);
				return ar;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("合同应收实收差异查询异常:",e);
		}
		return ar;
	}

	@RequestMapping(value = "contractDiffInfoExport")
	public void contractDiffInfoExport(PaymentStagesDto paymentStagesDto,HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:businessChange:export"))){
				User user = ShiroUtil.getCurrentUser();
				paymentStagesDto.setMerchantId(user.getMerchantId());
				if(paymentStagesDto.getProjectId() ==null){
					paymentStagesDto.setProjectId(153L);
				}
				paymentStagesDto.setExport(true);
				String[] name = new String[]{"合同应收实收差异"};
				List<String[]> headerList = new ArrayList<String[]>();
				List<String[]> numberList = new ArrayList<String[]>();
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>();
				String[] header = new String[]{
						"项目","项目名称","业态","楼栋","单元","房间","简短房号","房间全称","合同类别","合同协议编号"
						,"客户名称","付款方式","签约日期","网签日期","业务归属日期","应收款类型","应收款名称","应收款标识（⊙部分收款 ! 多收）","应收款日期","应收款金额"
						,"欠款","逾期天数","成交总价与已收款之间的差额","置业顾问","应交款备注","是否工抵房","合同备注"
				};
				headerList.add(header);
				String[] numberHeader = new String[]{
						"应收款金额","欠款","逾期天数","成交总价与已收款之间的差额"
				};
				numberList.add(numberHeader);

				Project project = projectServiceFacade.findById(153L).getEntity();

				NeedReceiveRefundInfoDto needReceiveRefundDto = new NeedReceiveRefundInfoDto();
				needReceiveRefundDto.setAccessCode(project.getAccessCode());
				needReceiveRefundDto.setBusinessType("2");
				needReceiveRefundDto.setStatus("1");
				needReceiveRefundDto.setDocType("0");
				needReceiveRefundDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				needReceiveRefundDto.setIsExport("1");
				if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateBefore())){
					needReceiveRefundDto.setReceivablesDateBefore(DateUtils.parseDate(paymentStagesDto.getCheckDateBefore()+" 00:00:00", DateUtils.parsePatterns[3]));
				}
				if(StringUtils.isNotBlank(paymentStagesDto.getCheckDateAfter())){
					needReceiveRefundDto.setReceivablesDateAfter(DateUtils.parseDate(paymentStagesDto.getCheckDateAfter()+" 23:59:59", DateUtils.parsePatterns[3]));
				}
				Page<NeedReceiveRefundInfo> needResponse = needReceiveRefundServiceFacade.findPageByDtoReport(needReceiveRefundDto, PageUtil.begin(1, 10), 10);
				List<NeedReceiveRefundInfo> psLs = needResponse.getRows();

				List<PaymentStages> resultList = new ArrayList<>();
				contractDiffData(psLs, resultList, project, true);

				List<Map<String, String>> listMap = contractDiffInfoList(resultList, header);
				list.add(listMap);
				ExcelUtil.exportExcelForNumber(list, headerList, numberList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("收款明细导出异常:",e);
		}
	}

	private void contractDiffData(List<NeedReceiveRefundInfo> psLs, List<PaymentStages> resultList, Project project, boolean exportFlag){
		for(NeedReceiveRefundInfo needReceiveRefund : psLs){
			PaymentStages paymentStages = new PaymentStages();

			paymentStages.setProjectName(project.getProjectName());
			paymentStages.setContactType("网签");
			paymentStages.setBillType("否");

			String combinedName = needReceiveRefund.getCombined_name().replaceAll("-->1-->", "-->");
			String[] roomNameArray = combinedName.split("-->");
			paymentStages.setAgentName(roomNameArray[0] + "-" + roomNameArray[1]);

			paymentStages.setCombinedName(combinedName.replaceAll("-->", "-"));
			paymentStages.setBuildingName(roomNameArray[2]);
			paymentStages.setRoomName(roomNameArray[roomNameArray.length - 1]);
			paymentStages.setGroupName(roomNameArray[2] + "-" + roomNameArray[roomNameArray.length - 1]);

			paymentStages.setNeedBankFund(needReceiveRefund.getTotalReceivablesAmount().toString());
			BigDecimal haveAmt1 = needReceiveRefund.getTotalReceivablesAmount().subtract(needReceiveRefund.getReceivedAmount());
			paymentStages.setHaveBankFund(haveAmt1.toString());
			paymentStages.setNeedTime1(needReceiveRefund.getReceivablesDate()!=null?DateUtils.dateToString(needReceiveRefund.getReceivablesDate(),DateUtils.parsePatterns[1]):"");

			if(needReceiveRefund.getReceivedAmount().compareTo(new BigDecimal(0))==1){
				paymentStages.setReceivedFlag("⊙");
			}else{
				paymentStages.setReceivedFlag("");
			}

			if(needReceiveRefund.getReceivablesDate()!=null){
				long expectedDays = DateUtils.getDaySub(DateUtils.dateToString(needReceiveRefund.getReceivablesDate(),DateUtils.parsePatterns[1]), DateUtils.getDate(DateUtils.parsePatterns[1]));
				paymentStages.setExpectedDays(expectedDays);
			}

			if(HousingFundTypeEnum.FUNDTYPE_1.getNo().equals(needReceiveRefund.getHousingFundType())){
				paymentStages.setPaymentType("其它");
			}else if(HousingFundTypeEnum.FUNDTYPE_7.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_11.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_18.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_19.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_28.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_36.getNo().equals(needReceiveRefund.getHousingFundType())
					||HousingFundTypeEnum.FUNDTYPE_37.getNo().equals(needReceiveRefund.getHousingFundType())){
				paymentStages.setPaymentType("贷款类房款");
			}else {
				paymentStages.setPaymentType("非贷款类房款");
			}
			paymentStages.setHousingFundType(HousingFundTypeEnum.getByNo(needReceiveRefund.getHousingFundType()).getDes());
			paymentStages.setUserName(needReceiveRefund.getUserName());
			paymentStages.setIndustMark(needReceiveRefund.getIndustMark());

			//客户名称
			if(!exportFlag) {
				FamilyMemberDto fmd = new FamilyMemberDto();
				fmd.setMemberType("4");
				fmd.setBuyId(needReceiveRefund.getRelationId());
				ResponseList<FamilyMember> familyMemberResponseList = familyMemberServiceFacade.findByDto(fmd);

				if (familyMemberResponseList.getEntity() != null) {
					StringBuffer coownerName = new StringBuffer();
					for (FamilyMember familyMember : familyMemberResponseList.getEntity()) {
						coownerName.append(familyMember.getMemberName() + ";");
					}
					coownerName.deleteCharAt(coownerName.length() - 1);
					paymentStages.setCoownerName(needReceiveRefund.getCustomer_name() + ";" + coownerName.toString());
				} else {
					paymentStages.setCoownerName(needReceiveRefund.getCustomer_name());
				}
			}else{
				if(StringUtils.isBlank(needReceiveRefund.getCustomerFamilyName())) {
					paymentStages.setCoownerName(needReceiveRefund.getCustomer_name());
				}else{
					paymentStages.setCoownerName(needReceiveRefund.getCustomer_name() + ";" + needReceiveRefund.getCustomerFamilyName());
				}
			}

			String paymentMethod = PaymentMethodEnum.getByNo(needReceiveRefund.getSignPaymentMethod()).getDes();
			paymentStages.setPaymentMethod("2".equals(needReceiveRefund.getDecorationPaymentMethod())?"首付分期【"+paymentMethod+"】":paymentMethod);
			paymentStages.setSignCode(needReceiveRefund.getSignCode());
			paymentStages.setSignDate(needReceiveRefund.getSignDate()!=null?DateUtils.dateToString(needReceiveRefund.getSignDate(), DateUtils.parsePatterns[1]):"");
			paymentStages.setSubscribeDate(needReceiveRefund.getAttributionDate()!=null?DateUtils.dateToString(needReceiveRefund.getAttributionDate(), DateUtils.parsePatterns[1]):"");

			BigDecimal needTotal = needReceiveRefund.getNeedReceivablesAmount()!=null?needReceiveRefund.getNeedReceivablesAmount():new BigDecimal(0);
			BigDecimal haveTotal = needReceiveRefund.getHaveRealAmount()!=null?needReceiveRefund.getHaveRealAmount():new BigDecimal(0);
			paymentStages.setTotalBalance(needTotal.subtract(haveTotal));
			paymentStages.setTotalBalanceAmount(paymentStages.getTotalBalance().toString());

			resultList.add(paymentStages);
		}
	}

	/**
	 * 组装导出审算台账数据
	 */
	private List<Map<String, String>> contractDiffInfoList(List<PaymentStages> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				int n = 0;
				PaymentStages data = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[n++]+"_"+i, data.getProjectName() != null ?data.getProjectName():"");
				map.put(head[n++]+"_"+i, data.getAgentName() != null ?data.getAgentName():"");
				map.put(head[n++]+"_"+i, data.getIndustMark() != null ?data.getIndustMark():"");
				map.put(head[n++]+"_"+i, data.getBuildingName() != null ?data.getBuildingName():"");
				map.put(head[n++]+"_"+i, "");
				map.put(head[n++]+"_"+i, data.getRoomName() != null ?data.getRoomName():"");
				map.put(head[n++]+"_"+i, data.getGroupName() != null ?data.getGroupName():"");
				map.put(head[n++]+"_"+i, data.getCombinedName() != null ?data.getCombinedName():"");
				map.put(head[n++]+"_"+i, data.getContactType() != null ?data.getContactType():"");
				map.put(head[n++]+"_"+i, data.getSignCode() != null ?data.getSignCode():"");

				//11
				map.put(head[n++]+"_"+i, data.getCoownerName() != null ?data.getCoownerName():"");
				map.put(head[n++]+"_"+i, data.getPaymentMethod() != null ?data.getPaymentMethod():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSignDate())?data.getSignDate().substring(0,10):"");

				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSignDate())?data.getSignDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getSubscribeDate())?data.getSubscribeDate().substring(0,10):"");
				map.put(head[n++]+"_"+i, data.getPaymentType() != null ?data.getPaymentType():"");

				map.put(head[n++]+"_"+i, data.getHousingFundType() != null ?data.getHousingFundType():"");
				map.put(head[n++]+"_"+i, data.getReceivedFlag() != null ?data.getReceivedFlag():"");
				map.put(head[n++]+"_"+i, StringUtils.isNotBlank(data.getNeedTime1())?data.getNeedTime1().substring(0,10):"");

				map.put(head[n++]+"_"+i, data.getNeedBankFund() != null ?data.getNeedBankFund().toString():"");

				//21
				map.put(head[n++]+"_"+i, data.getHaveBankFund() != null ?data.getHaveBankFund().toString():"");
				map.put(head[n++]+"_"+i, data.getExpectedDays() != null ?data.getExpectedDays()+"":"");
				map.put(head[n++]+"_"+i, data.getTotalBalanceAmount() != null ?data.getTotalBalanceAmount():"");
				map.put(head[n++]+"_"+i, data.getUserName() != null ?data.getUserName():"");
				map.put(head[n++]+"_"+i, "");

				map.put(head[n++]+"_"+i, data.getBillType() != null ?data.getBillType():"");
				map.put(head[n++]+"_"+i, "");

				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出合同应收实收差异数据错误：{}",e);
		}
		return listMap;
	}
}

